///////////////////////////////////////////////////
/// toto Code
/// $Id: thread.h 2 2009-12-14 12:41:06Z tonyjobmails $
/// $Date: 2009-12-14 12:41:06 +0000 (Mon, 14 Dec 2009) $
/// $Author: tonyjobmails $
/// $Revision: 2 $
/// E-mail: tonyjobmails@gmail.com
/// filename: thread.h
/// function: 线程基类的定义
///////////////////////////////////////////////////

#ifndef __THREAD__H
#define __THREAD__H

#include <string>
#include <pthread.h>
#includde <unistd.h>
#include "mutex.h"
#include "base.h"

namespace toto
{
	enum
	{
		THREAD_STATE_CREATE = 0,		/// 线程对象创建
		THREAD_STATE_ALIVE,				/// 线程运行
		THREAD_STATE_SLEEP,				/// 线程休眠
		THREAD_STATE_END,					/// 线程结束
	};
	
	class xthread
	{
		public:
			xthread(const std::string &name = std::string("thread"), unsigned short state(THREAD_STATE_CREATE), bool joinable(true), pthread_t thread(0))
				: this->thread_name(name), this->state(state), this->joinable(joinable), this->thread(thread)
			{}
			virtual ~xthread()
			{}
			
			/// 得到线程ID
			static pthread_t get_thread_id()
			{
				pthread_self();
			}
			
			/// 线程休眠(秒)
			static void sleep(const long sec)
			{
				sleep(sec);
			}
			
			/// 线程休眠(毫秒)
			static void msleep(const long msec)
			{
				usleep(msec * 1000);
			}
			
			/// 线程休眠(微秒)
			static void usleep(const unsigned long usec)
			{
				usleep(usec);
			}
			
			/// 得到线程名
			std::string get_name()
			{
				return this->thread_name;
			}
			
			/// 线程是否是joinable的
			bool is_joinable()
			{
				return joinable;
			}
			
			/// 线程是否是活动状态
			bool is_alive()
			{
				return (this->state == THREAD_STATE_ALIVE);
			}
			
			/// 线程是否是休眠状态
			bool is_sleep()
			{
				return (this->state == THREAD_STATE_SLEEP);
			}
			
			/// 线程是否是结束状态
			bool is_end()
			{
				return (this->state == THREAD_STATE_END);
			}
			
			/// 设置线程为结束状态
			void end()
			{
				this->state = THREAD_STATE_END;
			}
			
			/// 线程开始
			bool start();
			
			/// 线程方法
			static bool thread_func(void *arg);
			
			/// 线程主回调函数，派生类需要重新定义
			virtual bool run() = 0;
			
			/// 等待线程结束
			void join();
			
		private:
			std::string thread_name;			/// 线程名
			pthread_t thread;					/// 线程ID
			unsigned short state;				/// 线程状态
			bool joinable;							/// 线程是否join
			xmutex mutex;						/// 互斥锁
			xcond cond;							/// 条件变量
	};
};

#endif	/// __THREAD__H